<template>
  <div id="edit_content" class='form'    :style="{width:(columnWidth+75)*column +'px'}" :class="{single:column==1}">
    <div v-if="!columnModelData" class="spin"><d-spin></d-spin></div>
    <el-form v-if="columnModelData" :model="columnModelData" :rules="editFormRules" ref="editForm" label-position="left"   class="clearfix" >
      <template v-if="columnEdit" v-for="(value,key) in columnEdit">

        <el-form-item   v-if="value.cellType == 'date' " class="form_item" :class="{'is-required':value.isMust}"     :label="value.title"   :prop="value.name">
          <el-date-picker
            v-model="columnModelData[value.name]"
            placeholder="selecte Date"
            :style="{width:columnWidth+'px'}"
            format="yyyy-MM-dd"
            type="date"
            :disabled = "!value.isEdit"
            >
          </el-date-picker>
        </el-form-item>
        <el-form-item  v-if="value.cellType=='treeSelect' " class="form_item"  :class="{'is-required':value.isMust}"    :label="value.title"   :prop="value.name" :disabled = '!value.isEdit'>
          <div class="dayhr_drop_select" :data-value="columnModelData[value.name]"  :data-disabled="stringifyJSON(value.isDisabled)"   :data-keyValue="stringifyJSON(value.keyValueBean )" :data-name="value.name" :data-title = "value.title"></div>
        </el-form-item>

        <el-form-item   v-if="value.cellType == 'text'|| !value.cellType" class="form_item" :class="{'is-required':value.isMust}"     :label="value.title"   :prop="value.name" :disabled = '!value.isEdit'>
          <el-input  :style="{width:columnWidth+'px'}" :type="value.cellType||'text'" :name="value.name" v-model="columnModelData[value.name]" :disabled="!value.isEdit"></el-input>
        </el-form-item>

        <el-form-item  v-if="value.cellType == 'textarea'" class="form_item" :class="{'is-required':value.isMust}"     :label="value.title"   :prop="value.name" :disabled = '!value.isEdit'>
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            :disabled="!value.isEdit"
            :name="value.name" v-model="columnModelData[value.name]">
            :style="{width:columnWidth+'px'}"
          </el-input>
        </el-form-item>

        <el-form-item v-if="value.cellType == 'select'" class="form_item" :class="{'is-required':value.isMust}"     :label="value.title"   :prop="value.name" :disabled = '!value.isEdit'>
          <el-select :style="{width:columnWidth+'px'}" v-model="columnModelData[value.name]" placeholder="selecte"  :disabled = "!value.isEdit">
            <el-option
              v-for="item in select[value.name]"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </template>
      <el-form-item  class="form_btn_group" :class="{single:column==1&&formType=='add'}">
        <el-button v-if="formType=='add'" type="primary"  @click.native="validForm(false)" >save and new</el-button>
        <el-button type="primary" @click.native="validForm(true)">save</el-button>
        <el-button @click="$emit('close')">Cancel</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>


  import dSpin from '../../components/common/Spin.vue'
  //树组件
  var dayhrDropSelect = require("../../assets/js/plugins/dayhrDropSelect/dayhrDropSelect"); //下拉

    export default{
      components:{
        dSpin
      },
      computed:{
        columnEdit:function () {
          return this.formData.columnEdit.filter(function(value){
            return value.isEditShow;
          });
        },
        columnData:function () {
          var data = this.formData.data;
          return this.getColumnEditObj(this.columnEdit,'name',"",data);

        }
      },
      created:function () {
        this.columnWidth = this.columnWidthInit;
        var option = Object.assign({},this.formOption);
        this.formData = option.formData;
        this.formType = option.formType;
        this.formInfoSetId = option.formInfoSetId;
        this.navigationCondition = option.navigationCondition;
        this.editCondition = option.editCondition;
        this.init();
      },
      mounted:function () {

      },
      data:function () {
        return{
          columnWidth:null,
          formData:null,
          formType:null,
          formInfoSetId:null,
          navigationCondition:null,
          editFormRules:{

          },
          columnModelData:null,
          columnEditObj:{},
          showSpin:false,
          drops:{},
          column:1,
          isClose:false,
          positionDrop:null,
          positionDropData:null,
          treeData:{},
          select:{
            'supervisor':[
            ]
          },
          dropSelect:{},

        }
      },
      methods: {
        init:function () {
           this.initWidth();
           this.initFormAndTree();
        },
         stringifyJSON:function(value){
           return JSON.stringify(value);
        },
        //初始化表单里面的树
        initEditTree:function () {
          var t = this;
          var $editTree = $(t.$el).find('.dayhr_drop_select');
          var len = $editTree.length;
          for(var i=0;i<len;i++){
            var param = JSON.parse($editTree.eq(i).attr('data-keyValue'));
            var id = 'id' + new Date().getTime() + parseInt(Math.random(1000)*1000);
            $editTree.eq(i).prop('id',id);
            var name = $editTree.eq(i).attr('data-name');
            var value = $editTree.eq(i).attr('data-value');
            var title = $editTree.eq(i).attr('data-title');
            var isDisabled = $editTree.eq(i).attr('data-disabled');
            //初始化 tree
             t.drops[name]= new dayhrDropSelect({
                id:id,
                width:t.columnWidth-2,
                maxHeight:250,
                placeholder:"select " + title,
                data:[],
                name:name,
                onSelected:function(oSelect, type){
                 t.dropSelect[oSelect.key] = oSelect.value;
                  t.columnModelData[oSelect.key] = oSelect.value;
                 //点击组织带work location
                  if(t.formInfoSetId == 'comp_person_list'){
                    if(oSelect.key == 'org_id'){
                      t.$store.dispatch('getLocationByOrganization',
                        {
                          param: {customParam:{org_id:oSelect.value}},
                          success: (data)=> {
                            if(data.maps&&data.maps.length){
                              var workLocation = data.maps[0].work_location || "";
                              t.columnModelData['work_location'] = oSelect.value;
                            }
                          }
                        });
                      }
                  }

                  //点击组织带出职位和work location ,点击职位带出上级人
                  if(t.formInfoSetId == 'comp_person_base_office'){
                    if(oSelect.key == 'org_id'){
                      t.$store.dispatch('getLocationByOrganization',
                        {
                          param: {customParam:{org_id:oSelect.value}},
                          success: (data)=> {
                           if(data.maps&&data.maps.length){
                              var workLocation = data.maps[0].work_location || "";
                              t.columnModelData['work_location'] = oSelect.value;
                            }
                         }
                      });
                      if(t.positionDrop&&t.positionDropData){
                        var data = t.positionDropData;
                        var childrenData = t.getTreeData(data);
                        var positionTreeData = childrenData[oSelect.node.name];
                        t.positionDrop.updateTreeJson(positionTreeData);
                        t.positionDrop.setValue(t.dropSelect['pos_id']);
                      }

                    }
                    if(oSelect.key == 'pos_id'){
                      t.$store.dispatch('getSupervisorByPosition',
                        {
                          param: {customParam:{pos_id:oSelect.value}},
                          success: (data)=> {
                          if(data.maps&&data.maps.length){
                            t.select['supervisor'] = data.maps.map(function(item){
                              return{
                                label:item.first_name,
                                value:item.person_id
                              }
                            });
                          }else{
                             t.select['supervisor'] = [];
                          }
                         }
                      });
                    }
                  }
                }
              });

            t.$store.dispatch('getKeyValueData',
            {
              param:param,
              extra:{id:id,name:name,value:value,title:title,isDisabled:isDisabled},
              success:(data,extraObj)=>{
                  data = data.beans;
                var drop = t.drops[extraObj.name];
                drop.updateTreeJson(data);
                drop.setValue(extraObj.value);
                t.dropSelect[extraObj.name] = extraObj.value;
                if(extraObj.isDisabled == 'true'){
                  drop.setDisabled(true);
                }
                if(extraObj.name == 'pos_id'){
                   t.positionDropData = data;
                   t.positionDrop = drop;
                   if(t.dropSelect['org_id']){
                     var data = t.positionDropData;
                     var childrenData = t.getTreeData(data);
                     var positionTreeData = childrenData[t.dropSelect['org_id']];
                     t.positionDrop.updateTreeJson(positionTreeData);
                     t.positionDrop.setValue(extraObj.value);

                   }
                }
              }
            }
           );
          }
        },
        getTreeData:function(data){
          var t = this;
          var obj = t.treeData;
          for(var i = 0;i<data.length;i++){
          if(data[i].children){
            t.getTreeData(data[i].children);
              obj[data[i].name] = data[i].children;
            }else{
              obj[data[i].name] = [];
            }
          }
          return obj;
        },
        initWidth:function () {
          var len = this.columnEdit.length;
          this.column = len>20?3:len>10?2:1;
        },
        initFormAndTree:function () {
          var t = this;
          t.editFormRules = t.setFormRule();
          t.columnModelData = Object.assign({},this.columnData);
          t.$nextTick(function(){
            t.initEditTree();
          });
        },
        getColumnEditObj:function(columnEditList,key,value,data){
          var data_arr = columnEditList;
          var key = key;
          var obj = {};
          if(data_arr&&data_arr.length&&key){
            for(var i=0;i<data_arr.length;i++){
              obj[data_arr[i][key]] = value!=null?value:data_arr[i];
            }
          }
          return Object.assign(obj,data);
        },
        setFormRule:function(){
          var t = this;
          t.columnEditObj = t.getColumnEditObj(t.columnEdit,'name');
          var oRules={};
          for(var i in t.columnEditObj){
            oRules[ t.columnEditObj[i].name] = [];
            var validatePass = (rule, value, callback) => {
              var field = t.columnEditObj[rule.field];
              if(field.isMust){
                if(!value){
                  callback(new Error(field.title+'  is required'));
                }else{
                  callback();
                }
              }else if(field.regExpress){
                var _reg = new RegExp(field.regExpress);
                if (!_reg.test(value)) {
                  callback(new Error(field.title+' format is not correct'));
                }else{
                  callback();
                }
              }else {
                callback();
              }
            };
            oRules[t.columnEditObj[i].name].push(
              { validator: validatePass, trigger: 'change' }
            );

          }
          return oRules;
        },
        validForm:function (isClose) {
          this.$refs.editForm.validate((valid) => {
            if (valid) {
              this.isClose = isClose;
              this.submitForm();
            } else {
              console.log('error submit!!');
              return false;
            }
          });
        },
        clearForm:function(){
          var t = this;
          t.$refs.editForm.resetFields();
          for(var i in t.drops){
            t.drops[i].setValue("");
          }
        },
        submitForm:function () {
          var t = this;
          //add提交表单
          var formValue = t.getFormValue(t.columnModelData);

          if( t.formType == 'add'){
            if(t.editCondition){
              formValue.push(t.editCondition);
            }
            var param = {
              infoSetId:t.formInfoSetId,
              dataList:formValue,
            }
            t.$store.dispatch("add",{param:param,success:function () {
              t.$message({
                message: 'add Success',
                type: 'success'
              });
               t.$emit('update');
               t.clearForm();
              if(t.isClose){
                t.$emit('close');
              }
            }});
          }
          //update 提交表单

          if( t.formType == 'update'){
            var param = {
              infoSetId:t.formInfoSetId,
              dataList:formValue,
              uuid:t.columnData.uuid
            }

            t.$store.dispatch("update",{param:param,success:function () {
              t.$message({
                message: 'update Success',
                type: 'success'
              });
              t.$emit('close');
              t.$emit('update');
            }});
          }
        },
        getFormValue:function(data){
          var t = this;
          var paramValue=[];
          for(var i in data){
            if(data[i]){
              //如果是日期，格式化yyyy-MM-dd格式
              if(Object.prototype.toString.call(data[i])=='[object Date]'){
                  data[i] = Tools.dateFormat(data[i],'yyyy-MM-dd');
              }
              //update只要值变了的
              if(t.formType == 'update' &&data[i] != t.columnData[i]){
                paramValue.push({key:i,value:data[i]});
              }else if(t.formType == 'add'){
                paramValue.push({key:i,value:data[i]});
              }
            }
          }
          console.log(paramValue);
          return paramValue;
        }
      },
      props:{
        formOption:{
          type:Object,
          default:function(){
            return {
              formData:null,
              formType:null,
              formInfoSetId:null,
              navigationCondition:null,
              editCondition:null
            }
          }
        },
        columnWidthInit:{
          type:Number,
          default:220
        }
      }
    }
</script>
<style rel="stylesheet/scss" type="text/css" lang="scss" scoped>
  @import "../../assets/css/variable";
  .form {
    padding: 20px;
    margin: 0 auto;
    min-height: 150px;
    min-width: 330px;
    &.single{
      text-align: center;
    }
    .form_item{
      padding: 0 35px;
      display: inline-block;
      margin-bottom: 20px;
      vertical-align: middle;
    }
    .form_btn_group{
      width: 100%;
      text-align: right;
      margin:30px 0 0 0;
      &.single{
        text-align: center;
      }
    }
    .msg-wrap{
      position: fixed;
      margin-top:6px;
    }
    .input_line{
      /*height: 40px;*/
      line-height: 38px;
      float: left;
      .input_line_left{
        width: 160px;
        text-align: right;
        float: left;
        padding: 0 10px;
        .label{
          text-align: right;
          padding-right: 20px;
          position: relative;
          display: inline-block;
          width: 100%;
          box-sizing: border-box;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          vertical-align: middle;
          font-weight: bold;
          &.isMust:after{
            content: '*';
            color: #ff5500;
            position: absolute;
            right: 2px;
            top: 6px;
            font-size: 22px;
          }
        }
      }
      .input_line_right{
        width: 200px;
        text-align: left;
        float: left;
        .input{
          width: 170px;
          box-sizing: border-box;
          padding: 0 12px;
          color: #666;
        }
        .textarea{
          width: 170px;
          height: 60px;
        }
      }
    }
    .btn_group{
      margin-top: 40px;
      button{
        margin: 0 12px;
      }
      text-align: center;
    }
  }
</style>
